import { defineStore } from 'pinia'
import { computed, reactive, watch } from 'vue'
import { useDebounce } from '@/hooks/debounce'

export const useThemeStore = defineStore('theme', () => {
    const list = reactive([{
        key: 'auto',
        name: '跟随系统模式',
        info: '与手机设置保持一致的浅色&深色模式',
        active: true,
        value: 'light',
    }, {
        key: 'light',
        name: '浅色模式',
        info: '',
        active: false,
        value: 'light',
    }, {
        key: 'dark',
        name: '深色模式',
        info: '',
        active: false,
        value: 'dark',
    },])

    const syncAutoTheme = async () => {
        const theme = (await uni.getSystemInfo()).theme
        list[0].value = theme
        return theme
    }

    const storageThemeSetting = useDebounce(() => {
        uni.setStorage({
            key: 'theme',
            data: current.value.key
        })
    }, 2000)

    const change = (index) => {
        for (let i = 0; i < list.length; i++) {
            if (i == index) {
                list[i].active = true
            } else {
                list[i].active = false
            }
        }
    }

    const handleThemeChange = () => {
        function handleOnChange(res) {
            list[0].value = res.theme
            change(0)
        }

        if (current.value.key == 'auto') {
            uni.onThemeChange(handleOnChange)
        } else {
            uni.offThemeChange(handleOnChange)
        }
    }

    const current = computed(() => {
        return list.find(i => i.active)
    })

    const theme = computed(() => {
        return current.value.value
    })

    watch(list, () => {
        if (current.value.key == 'auto') syncAutoTheme()
        handleThemeChange()
        storageThemeSetting()
    }, {
        immediate: true,
        deep: true,
        flush: 'post',
    })

    const init = () => {
        uni.getStorage({
            key: 'theme',
            success: res => {
                if (['auto', 'light', 'dark'].includes(res.data)) {
                    const index = list.findIndex(i => i.key == res.data)
                    change(index)
                } else {
                    change(0)
                }
            },
            fail: err => {
                change(0)
            }
        })
    }

    return {
        theme,
        current,
        list,
        init,
        change,
    }
})